﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DAL;

namespace Admin
{
    public partial class MainForm : Form
    {
        public const int MAXCOURSENUM = 12000;

        struct Course
        {
            public string CourseName;
            public string Time;
            public string CapacityForUnder;
            public string CapacityForGra;
            public string Credit;
            public string CourseID;
            public string CourseSn;
            public string Department;
            public string Type;
            public string Introduction;
            public bool IsExisting;
            // teacher
            public string TeacherName;
            public string TeacherDepartment;
            public string TeacherID;
            public string TeacherGender;
            public string TeacherPosition;
            // other
            public string courseHref;
            public string teacherHref;
        }

        private Course[] courses = new Course[MAXCOURSENUM];

        private int CourseCount = 1;
        private int CourseNum = 0;
        private int FirstPageCount = 1;
        private int FirstPageNum = 0;

        private int _state = 0;

        private string _inputUrl;
        private int _year;
        private int _term;
        private string[] _termStatement = { "", "秋季学期", "春季学期", "夏季学期" };

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            webBrowser.Navigate("http://info.tsinghua.edu.cn");
            comboBox1.SelectedIndex = 0;
            button3.Enabled = false;
            tabControl1.TabPages.Remove(tabPage3);
        }

        private void AnalyInputUrl()
        {
            int pos;
            if ((pos = _inputUrl.IndexOf("20")) != -1)
            {
                _year = int.Parse(_inputUrl.Substring(pos, 4));
                _term = int.Parse(_inputUrl.Substring(pos + 10, 1));
                label2.Text = "您选择了 " + _year.ToString() + " 至 "
                            + (_year + 1).ToString() + " 学年 "
                            + _termStatement[_term] + " 的课程";
                label2.ForeColor = Color.Black;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 分析用户输入页面
            _inputUrl = TextBox1.Text;
            AnalyInputUrl();
            // 使能导入数据
            button3.Enabled = true;
            // 加载一级页面第一页
            _state = 1;
            webBrowser.Navigate(_inputUrl);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            webBrowser.Navigate("http://info.tsinghua.edu.cn");
            label2.Text = "您尚未确认网址";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            // 使能timer1
            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Interval = 500;

            if (_state == 1)
            {
                string linestr;
                var reader = new StreamReader(webBrowser.DocumentStream, Encoding.GetEncoding("GBK"));

                while (!reader.EndOfStream)
                {
                    linestr = reader.ReadLine();
                    if (linestr == null || linestr.IndexOf("var gridData = [") != -1)
                        break;
                }
                while (!reader.EndOfStream)
                {
                    linestr = reader.ReadLine();
                    if (linestr.IndexOf("];") != -1 || (FirstPageCount > FirstPageNum && FirstPageNum >= 1))
                        break;
                    if (linestr.IndexOf("[") != -1)
                    {
                        linestr = reader.ReadLine();    // 院系
                        courses[CourseCount].Department = linestr.Substring(linestr.IndexOf('\"') + 1, linestr.LastIndexOf('\"') - linestr.IndexOf('\"') - 1);
                        linestr = reader.ReadLine();    // 课程号
                        courses[CourseCount].CourseID = linestr.Substring(linestr.IndexOf('\"') + 1, linestr.LastIndexOf('\"') - linestr.IndexOf('\"') - 1);
                        linestr = reader.ReadLine();    // 课序号
                        courses[CourseCount].CourseSn = linestr.Substring(linestr.IndexOf('\"') + 1, linestr.LastIndexOf('\"') - linestr.IndexOf('\"') - 1);
                        reader.ReadLine();              // 空行
                        reader.ReadLine();              // 空行
                        linestr = reader.ReadLine();    // 课程名和课程链接
                        if (linestr.IndexOf('<') == -1)
                        {
                            linestr = reader.ReadLine();
                            courses[CourseCount].CourseName = linestr.Substring(linestr.IndexOf('\"') + 1, linestr.LastIndexOf('\"') - linestr.IndexOf('\"') - 1);
                            courses[CourseCount].courseHref = "";
                        }
                        else
                        {
                            courses[CourseCount].CourseName = linestr.Substring(linestr.IndexOf('>') + 1, linestr.LastIndexOf('<') - linestr.IndexOf('>') - 1);
                            courses[CourseCount].courseHref = "http://zhjw.cic.tsinghua.edu.cn/" + linestr.Substring(linestr.IndexOf("href=\'") + 6, linestr.LastIndexOf("\' c") - linestr.IndexOf("href=\'") - 6);
                            reader.ReadLine();
                        }
                        reader.ReadLine();              // 空行
                        reader.ReadLine();              // 空行
                        linestr = reader.ReadLine();    // 学分
                        courses[CourseCount].Credit = linestr.Substring(linestr.IndexOf('\"') + 1, linestr.LastIndexOf('\"') - linestr.IndexOf('\"') - 1);
                        reader.ReadLine();              // 空行
                        reader.ReadLine();              // 空行
                        linestr = reader.ReadLine();    // 教师和教师链接
                        if (linestr.IndexOf('<') == -1)
                        {
                            reader.ReadLine();
                            courses[CourseCount].teacherHref = "";
                        }
                        else
                        {
                            courses[CourseCount].teacherHref = "http://zhjw.cic.tsinghua.edu.cn/" + linestr.Substring(linestr.IndexOf("href=\'") + 6, linestr.LastIndexOf("\' t") - linestr.IndexOf("href=\'") - 6);
                            reader.ReadLine();
                        }
                        reader.ReadLine();              // 空行
                        reader.ReadLine();              // 空行
                        linestr = reader.ReadLine();    // 本科生课容量
                        courses[CourseCount].CapacityForUnder = linestr.Substring(linestr.IndexOf('\"') + 1, linestr.LastIndexOf('\"') - linestr.IndexOf('\"') - 1);
                        linestr = reader.ReadLine();    // 研究生课容量
                        courses[CourseCount].CapacityForGra = linestr.Substring(linestr.IndexOf('\"') + 1, linestr.LastIndexOf('\"') - linestr.IndexOf('\"') - 1);
                        linestr = reader.ReadLine();    // 时间
                        courses[CourseCount].Time = linestr.Substring(linestr.IndexOf('\"') + 1, linestr.LastIndexOf('\"') - linestr.IndexOf('\"') - 1);
                        reader.ReadLine();              // 空行
                        linestr = reader.ReadLine();    // 课程类型
                        courses[CourseCount].Type = linestr.Substring(linestr.IndexOf('\"') + 1, linestr.LastIndexOf('\"') - linestr.IndexOf('\"') - 1);
                        courses[CourseCount].IsExisting = comboBox1.SelectedIndex == 0;
                        label5.Text = "正在进行第1步，共3步。该步骤已完成" + String.Format("{0:N1}", (double)FirstPageCount / (double)FirstPageNum * 100.0) + "%。";
                        CourseCount++;
                    }
                }
                while (FirstPageNum == 0 && !reader.EndOfStream)
                {
                    linestr = reader.ReadLine();
                    if (linestr == null || linestr.IndexOf("共 ") != -1)
                    {
                        FirstPageNum =
                            int.Parse(linestr.Substring(linestr.IndexOf("共 ") + 2,
                                                        linestr.IndexOf(" 页", linestr.IndexOf("共 ") + 2) - linestr.IndexOf("共 ") - 2));
                        CourseNum =
                            int.Parse(linestr.Substring(linestr.LastIndexOf("共 ") + 2,
                                                        linestr.LastIndexOf(" 条记录") - linestr.LastIndexOf("共 ") - 2));
                    }
                }

                if (FirstPageCount >= FirstPageNum)
                {
                    CourseCount = 1;
                    _state = 2;
                }
                else
                {
                    HtmlDocument doc = webBrowser.Document;
                    foreach (HtmlElement item in doc.All)
                    {
                        if (item.GetAttribute("href").IndexOf("javascript:turn(" + (FirstPageCount + 1).ToString() + ")") != -1)
                        {
                            item.InvokeMember("click");
                            FirstPageCount++;
                            break;
                        }
                    }
                }
            }

            if (_state == 2)
            {
                webBrowser.Navigate(courses[CourseCount].courseHref);
            }

            if (_state == 3)
            {
                webBrowser.Navigate(courses[CourseCount].teacherHref);
            }
        }

        private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (_state == 0)
            {
                HtmlDocument doc = webBrowser.Document;
                foreach (HtmlElement item in doc.All)
                {
                    if (item.GetAttribute("href").IndexOf("render") != -1)
                    {
                        label4.Text = "您已登录";
                        label4.ForeColor = Color.Black;
                        button1.Enabled = true;
                        break;
                    }
                }
            }

            if (_state == 3)
            {
                string linestr;
                var reader = new StreamReader(webBrowser.DocumentStream, Encoding.GetEncoding("GBK"));

                while (!reader.EndOfStream)
                {
                    linestr = reader.ReadLine();
                    if (linestr != null && linestr.IndexOf("教师号") != -1)
                    {
                        linestr = reader.ReadLine();
                        courses[CourseCount].TeacherID = linestr.Substring(linestr.IndexOf('>') + 1, linestr.LastIndexOf('<') - linestr.IndexOf('>') - 1);
                        break;
                    }
                }
                while (!reader.EndOfStream)
                {
                    linestr = reader.ReadLine();
                    if (linestr != null && linestr.IndexOf("姓名") != -1)
                    {
                        linestr = reader.ReadLine();
                        courses[CourseCount].TeacherName = linestr.Substring(linestr.IndexOf('>') + 1, linestr.LastIndexOf('<') - linestr.IndexOf('>') - 1);
                        break;
                    }
                }
                while (!reader.EndOfStream)
                {
                    linestr = reader.ReadLine();
                    if (linestr != null && linestr.IndexOf("性别") != -1)
                    {
                        reader.ReadLine();
                        reader.ReadLine();
                        linestr = reader.ReadLine();
                        courses[CourseCount].TeacherGender = linestr.Substring(linestr.LastIndexOf(' ') + 1);
                        break;
                    }
                }
                while (!reader.EndOfStream)
                {
                    linestr = reader.ReadLine();
                    if (linestr != null && linestr.IndexOf("职称") != -1)
                    {
                        reader.ReadLine();
                        reader.ReadLine();
                        linestr = reader.ReadLine();
                        if (linestr.IndexOf("</td>") == -1)
                            courses[CourseCount].TeacherPosition = linestr.Substring(linestr.LastIndexOf(' ') + 1);
                        else
                            courses[CourseCount].TeacherPosition = "";
                        break;
                    }
                }
                while (!reader.EndOfStream)
                {
                    linestr = reader.ReadLine();
                    if (linestr != null && linestr.IndexOf("电话") != -1)
                        break;
                    if (linestr != null && linestr.IndexOf("单位") != -1)
                    {
                        reader.ReadLine();
                        while (true)
                        {
                            linestr = reader.ReadLine();
                            if (linestr.IndexOf("</td>") != -1)
                                break;
                            string temp = "";
                            for (int i = 0; i < linestr.Length; i++)
                            {
                                if (linestr[i] != ' ' && linestr[i] != '\t')
                                {
                                    temp += linestr[i];
                                }
                            }
                            if (temp != "")
                            {
                                switch (temp)
                                {
                                    case "土木工程系":
                                        temp = "土木系";
                                        break;
                                    case "水利水电工程系":
                                        temp = "水利系";
                                        break;
                                    case "机械工程系":
                                        temp = "机械系";
                                        break;
                                    case "精密仪器与机械学系":
                                        temp = "精仪系";
                                        break;
                                    case "热能工程系":
                                        temp = "热能系";
                                        break;
                                    case "汽车工程系":
                                        temp = "汽车系";
                                        break;
                                    case "工业工程系":
                                        temp = "工业工程";
                                        break;
                                    case "电机工程与应用电子技术系":
                                        temp = "电机系";
                                        break;
                                    case "电子工程系":
                                        temp = "电子系";
                                        break;
                                    case "计算机科学与技术系":
                                        temp = "计算机系";
                                        break;
                                    case "微电子学研究所":
                                        temp = "微纳电子系";
                                        break;
                                    case "航天航空学院":
                                        temp = "航院";
                                        break;
                                    case "工程物理系":
                                        temp = "工物系";
                                        break;
                                    case "材料科学与工程系":
                                        temp = "材料系";
                                        break;
                                    case "数学科学系":
                                        temp = "数学系";
                                        break;
                                    case "生命科学学院":
                                        temp = "生命学院";
                                        break;
                                    case "地球系统科学研究中心":
                                        temp = "地球科学中心";
                                        break;
                                    case "交叉信息研究院":
                                        temp = "交叉信息院";
                                        break;
                                    case "化学工程系":
                                        temp = "化工系";
                                        break;
                                    case "经济管理学院":
                                        temp = "经管学院";
                                        break;
                                    case "公共管理学院":
                                        temp = "公共管理";
                                        break;
                                    case "人文社会科学学院":
                                        temp = "人文学院";
                                        break;
                                    case "中国语言文学系":
                                        temp = "中文系";
                                        break;
                                    case "外国语言文学系":
                                        temp = "外文系";
                                        break;
                                    case "新闻与传播学院":
                                        temp = "新闻学院";
                                        break;
                                    case "体育教研部":
                                        temp = "体育部";
                                        break;
                                    case "艺术教育中心":
                                        temp = "艺教中心";
                                        break;
                                    case "核能与新能源技术研究院":
                                        temp = "核研院";
                                        break;
                                    case "教育研究院":
                                        temp = "教研院";
                                        break;
                                    case "信息网络工程研究中心":
                                        temp = "网络中心";
                                        break;
                                    case "基础工业训练中心":
                                        temp = "训练中心";
                                        break;
                                    case "党委学生部":
                                        temp = "学生部";
                                        break;
                                    case "党委武装部":
                                        temp = "武装部";
                                        break;
                                    case "深圳研究生院":
                                        temp = "深研生院";
                                        break;
                                    case "清华大学医院":
                                        temp = "校医院";
                                        break;
                                    case "清华紫光集团":
                                        temp = "紫光集团";
                                        break;
                                }
                                courses[CourseCount].TeacherDepartment = temp;
                                break;
                            }
                        }
                    }
                }

                label5.Text = "正在进行第3步，共3步。该步骤已完成" + String.Format("{0:N1}", (double)CourseCount / (double)CourseNum * 100.0) + "%。";
                CourseCount++;

                if (CourseCount > CourseNum)
                {
                    CourseCount = 1;
                    _state = 4;
                    label5.Text = "所有数据已获取。";
                    button4.Enabled = true;
                }
            }

            if (_state == 2)
            {
                string _introduction = "";
                string linestr;
                var reader = new StreamReader(webBrowser.DocumentStream, Encoding.GetEncoding("GBK"));

                while (!reader.EndOfStream)
                {
                    linestr = reader.ReadLine();
                    if (linestr != null && linestr.IndexOf("课程简介") != -1)
                        break;
                }
                reader.ReadLine();
                while (!reader.EndOfStream)
                {
                    linestr = reader.ReadLine();
                    if (linestr != null && linestr.IndexOf("</td>") != -1)
                        break;
                    string temp = "";
                    for (int i = 0; i < linestr.Length; i++)
                    {
                        if (linestr[i] != ' ' && linestr[i] != '\t')
                        {
                            temp += linestr[i];
                        }
                    }
                    _introduction += temp;
                }
                courses[CourseCount].Introduction = _introduction;

                label5.Text = "正在进行第2步，共3步。该步骤已完成" + String.Format("{0:N1}", (double)CourseCount / (double)CourseNum * 100.0) + "%。";
                CourseCount++;

                if (CourseCount > CourseNum)
                {
                    CourseCount = 1;
                    _state = 3;
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            label18.Text = "正导入……";
            using (var context = new ModelContainer())
            {
                context.ExecuteStoreCommand("DELETE FROM CoursePlcaces");
                context.ExecuteStoreCommand("UPDATE Courses SET IsExisting = 0");
                for (int i = 1; i <= CourseNum; ++i)
                {
                    var tId = courses[i].TeacherID;
                    var teacher = context.Teachers.SingleOrDefault(t => t.TeacherId == tId);
                    if (teacher == null)
                    {
                        teacher = new Teacher
                                      {
                                          Department = courses[i].TeacherDepartment ?? "",
                                          Gender = courses[i].TeacherGender ?? "",
                                          Position = courses[i].TeacherPosition ?? "",
                                          TeacherId = courses[i].TeacherID ?? "",
                                          TeacherName = courses[i].TeacherName ?? ""
                                      };
                        context.Teachers.ApplyChanges(teacher);
                        context.SaveChanges();
                        teacher.AcceptChanges();
                    }
                    var cId = courses[i].CourseID;
                    var course = context.Courses.SingleOrDefault(t => t.CourseId == cId && t.Teacher.TeacherName == teacher.TeacherName) ??
                                 new DAL.Course
                                     {
                                         CourseName = courses[i].CourseName,
                                         Time = courses[i].Time,
                                         CapacityForUnder = courses[i].CapacityForUnder,
                                         CapacityForGra = courses[i].CapacityForGra,
                                         Credit = courses[i].Credit,
                                         CourseId = courses[i].CourseID,
                                         CourseSn = courses[i].CourseSn,
                                         Department = courses[i].Department,
                                         Type = courses[i].Type,
                                         Introduction = courses[i].Introduction,
                                         TeacherID = teacher.ID,
                                         IsExisting = courses[i].IsExisting,
                                         CourseInfo = new CourseInfo()
                                     };
                    if (course.ChangeTracker.State != ObjectState.Added)
                    {
                        course.IsExisting = courses[i].IsExisting;
                        course.MarkAsModified();
                    }
                    context.Courses.ApplyChanges(course);
                    context.SaveChanges();
                }
            }

            label18.Text = "恭喜，已完成。";
        }
    }
}